package com.ywgt.threadpool;


import java.util.concurrent.*;

public class ExecutorsTest {
    public static void main(String[] args) {
        //ExecutorService executorService = Executors.newSingleThreadExecutor();//单个线程
        //ExecutorService executorService = Executors.newCachedThreadPool();//根据需要创建线程，最大21亿个
        //ExecutorService executorService = Executors.newFixedThreadPool(5);//固定线程数
        ExecutorService executorService=new ThreadPoolExecutor(
                2,//一般时受理的线程数量
                Runtime.getRuntime().availableProcessors(),//线程池最大的线程数量
                3,//线程最长的存活时间，超过后关闭线程
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),//队列中最大待受理数量
                Executors.defaultThreadFactory(),//创建线程的工厂对象
                //new ThreadPoolExecutor.AbortPolicy() //超过线程z最大受理能力，就会报错
                //new ThreadPoolExecutor.CallerRunsPolicy()//超过最大线程受理能力后，使用原有线程进行执行，这里是main线程
                //new ThreadPoolExecutor.DiscardPolicy()//默认超过后不做处理，直接放弃
                new ThreadPoolExecutor.DiscardOldestPolicy()//默认超过后会尝试调用之前最先处理完成的线程，失败后直接放弃
        );
        try {
            for (int i = 1; i <=20; i++) {
                executorService.execute(
                        new Thread(()->{
                            System.out.println(Thread.currentThread().getName());
                        })
                );
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }
}
